#!/usr/bin/env python
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
from flask import Response
from flask import request
import sys
import os
import flask
import numpy as np
from io import BytesIO
import sys
import os
import base64
import time
import json
from PIL import Image


from urllib.parse import urlparse
# from com.aliyun.api.gateway.sdk import client
# from com.aliyun.api.gateway.sdk.http import request
# from com.aliyun.api.gateway.sdk.common import constant
import traceback
import urllib
import urllib.request
import urllib.error

import base64
import uuid

#
# def get_img_base64(img_file):
#     with open(img_file, 'rb') as infile:
#         s = infile.read()
#         return base64.b64encode(s)


def predict(url, appcode, img_base64, kv_config, old_format):
    if not old_format:
        param = {}
        param['image'] = img_base64
        if kv_config is not None:
            param['configure'] = json.dumps(kv_config)
        body = json.dumps(param)
    else:
        param = {}
        pic = {}
        pic['dataType'] = 50
        pic['dataValue'] = img_base64
        param['image'] = pic

        if kv_config is not None:
            conf = {}
            conf['dataType'] = 50
            conf['dataValue'] = json.dumps(kv_config)
            param['configure'] = conf

        inputs = {"inputs": [param]}
        # body = json.dumps(inputs)
        body = json.dumps(inputs).encode()

    headers = {'Authorization': 'APPCODE %s' % appcode}
    request = urllib.request.Request(url=url, headers=headers, data=body)
    try:
        response = urllib.request.urlopen(request, timeout=60)
        return response.code, response.headers, response.read()
    except urllib.error.HTTPError as e:
        return e.code, e.headers, e.read()


# import cv2


interface_path = os.path.dirname(__file__)
sys.path.insert(0, interface_path)  # 将当前文件的父目录加入临时系统变量


app = flask.Flask(__name__)


def file_iterator(file_path, chunk_size=512):
    """
        文件读取迭代器
    :param file_path:文件路径
    :param chunk_size: 每次读取流大小
    :return:
    """
    with open(file_path, 'rb') as target_file:
        while True:
            chunk = target_file.read(chunk_size)
            if chunk:
                yield chunk
            else:
                break


def to_json(obj):
    """
        放置
    :return:
    """
    return json.dumps(obj, ensure_ascii=False)

# def file(file):
# with open( r"C:\Users\dell\Desktop\600027.PNG", 'rb') as f:
#     base64_data = base64.b64encode(f.read())
#     s = base64_data.decode()
#     print('data:image/jpeg;base64,%s' % s)


def demo(file):
    appcode = 'd342bb0ba17249a9b41090beac38d882'
    url = 'https://form.market.alicloudapi.com/api/predict/ocr_table_parse'
    with open(file, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        s = base64_data.decode()
    # with open(r"C:\Users\dell\Desktop\021.jpg", "rb") as f:
    #     img_bin = f.read()  # 内容读取
    # img_file = r"C:\Users\dell\Desktop\000004  合并现金流量表1.png"
    # 如果输入带有inputs, 设置为True，否则设为False
    is_old_format = True
    config = {'format': 'xlsx', 'finance': False,
              'dir_assure': False}  # format 输出格式：html/json/xlsx;
    # 如果没有configure字段，config设为None
    # config = None
    img_base64data = s
    stat, header, content = predict(
        url, appcode, img_base64data, config, is_old_format)
    if stat != 200:
        print('Http status code: ', stat)
        print('Error msg in header: ',
              header['x-ca-error-message'] if 'x-ca-error-message' in header else '')
        print('Error msg in body: ', content)
        return {"xlsxFilePath": ""}
        # exit()
    if is_old_format:
        result_str = json.loads(
            content)['outputs'][0]['outputValue']['dataValue']
    else:
        result_str = content
    print("你好", result_str)

    res_obj = json.loads(result_str)

    uid = str(uuid.uuid1())
    xlsxFilePath = str("xlsxFile/output"+uid+".xlsx")
    print("到这里了1:"+xlsxFilePath)
    with open(xlsxFilePath, 'wb') as f:
        f.write(base64.b64decode(res_obj['tables']))
    print("到这里了2")
    return {"xlsxFilePath": xlsxFilePath}
    # return res_obj['tables']


if __name__ == '__main__':
    demo(r"C:\Users\dell\Desktop\600027X.PNG")
